package com.wzf.greattruth.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * 
 * @author wuzhengfei
 *
 */
public class AsyncClientHandler implements Runnable {

	AsynchronousSocketChannel asynSocketChannel;
	private String host;
	private int port;
	CountDownLatch latch;

	public AsyncClientHandler(String host, int port) {
		this.host = host;
		this.port = port;
		try {
			asynSocketChannel = AsynchronousSocketChannel.open();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		latch = new CountDownLatch(1);
		ClientConnectCompletionHandler connectCompletionHandler = new ClientConnectCompletionHandler();
		asynSocketChannel.connect(new InetSocketAddress(host, port), this, connectCompletionHandler);
		try {
			latch.await();
			asynSocketChannel.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
